extends TankTurret3D

@onready var main_aim_ray = $MainAimRay
@onready var cooldown_timer = $CooldownTimer
@onready var barrel_end_left = $BarrelEndLeft
@onready var barrel_end_right = $BarrelEndRight

var bullet = preload("res://Scenes/bullet.tscn")
var instance
var rng = RandomNumberGenerator.new()
var is_ready_to_fire = true
var left_barrel_to_fire = true

@rpc("any_peer", "call_local")
func spawn_projectile_left_barrel():
	instance = bullet.instantiate()
	instance.name = str(rng.randf_range(0, 10.0))
	instance.position = barrel_end_left.global_position
	instance.transform.basis = barrel_end_left.global_transform.basis
	instance.damage = damage
	var target = hitscan_target()
	if not (target is Vector3):
		var target_position = target[3].target_position
		instance.angle = target_position[1]/2.5

	get_tree().get_root().get_node('World').add_child(instance)

@rpc("any_peer", "call_local")
func spawn_projectile_right_barrel():
	instance = bullet.instantiate()
	instance.name = str(rng.randf_range(0, 10.0))
	instance.position = barrel_end_right.global_position
	instance.transform.basis = barrel_end_right.global_transform.basis
	instance.damage = damage
	var target = hitscan_target()
	if not (target is Vector3):
		var target_position = target[3].target_position
		instance.angle = target_position[1]/2.5

	get_tree().get_root().get_node('World').add_child(instance)

func fire():		
	if is_ready_to_fire:
		is_ready_to_fire = false
		play_shot_sound.rpc()
		apply_recoil()
		cooldown_timer.start()
		if left_barrel_to_fire:
			left_barrel_to_fire = false
			spawn_projectile_left_barrel.rpc()
		elif not left_barrel_to_fire:
			left_barrel_to_fire = true
			spawn_projectile_right_barrel.rpc()
		

func _on_cooldown_timer_timeout():
	is_ready_to_fire = true
